package 动态数组.栈;

import 动态数组.栈.接口.Stack;
import 动态数组.线性表.ArrayList;

import java.util.Iterator;

/**
 * 手写一个栈
 * @param <E> 操作的数据类型
 */
public class ArrayStack<E> implements Stack<E> {
    private ArrayList<E> list;

    public ArrayStack(){
        list = new ArrayList<E>();
    }

    public ArrayStack(int capacity){
        list = new ArrayList<>(capacity);
    }

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void push(E element) {
        list.add(element);
    }

    @Override
    public E pop() {
        return list.remove(list.size() - 1);
    }

    @Override
    public E peek() {
        return list.get(list.size() - 1);
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null){
            return false;
        }
        if (obj == this){
            return true;
        }
        if (getClass() != obj.getClass()){
            return false;
        }
        ArrayStack other = (ArrayStack) obj;
        //对象比对象，比较封装的栈里的list
        return list.equals(other.list);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("bottom [");
        if (isEmpty()){
            sb.append(']');
        }else {
            for (int i = 0;i < list.size(); i++){
                sb.append(list.get(i));
                if (i == list.size() -1){
                    sb.append("] top");
                }else {
                    sb.append(',');
                }
            }
        }
        return sb.toString();
    }

    @Override
    public Iterator iterator() {
        return list.iterator();
    }
}
